package net.alpenviewer.map;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class SRTMPreprocessor {

	/**
	 * Pre-processing. e.g. fill void-data.
	 */
	public void preprocess(SRTM srtm, File outputDir) {

		final int res = 1 + 3600 / srtm.arcSecond;
		final File src = srtm.src;
		final File out = new File(outputDir.getPath() + File.separator + src.getName());
		out.delete();
		final short[] hgtData = new short[res*res];

		{
			DataInputStream is = null;
			try {
				final byte[] buf = new byte[res*2];
				is = new DataInputStream(new FileInputStream(src));
				for (int y=0; y<res; y++) { // row (y-axis)
					is.read(buf);
					for (int x=0; x<res; x++) { // column (x-axis)
						final short height = (short) ( ((buf[x*2] & 0xff) << 0x8) | (buf[x*2+1] & 0xff) );
						hgtData[y*res+x] = height;															
					}
				}		
			} catch (IOException e) {
				throw new RuntimeException(e);
			}finally {
				try { is.close(); } catch (Exception ignored) {}
			}		
		}

		int voidCount = 0;
		for (int y=0; y<res; y++) { // row (y-axis)
			for (int x=0; x<res; x++) { // column (x-axis)
				final short height = hgtData[y*res+x];
				if (height == Short.MIN_VALUE) {
					voidCount++;
					// FIXME: fill void data
				}
			}
		}
		System.out.println(srtm + " has void data rate: " + ( (float)voidCount / (float)(res*res) ));		

		{
			DataOutputStream os = null;
			try {
				final byte[] buf = new byte[res*2];
				os = new DataOutputStream(new FileOutputStream(out));
				for (int y=0; y<res; y++) { // row (y-axis)				
					for (int x=0; x<res; x++) { // column (x-axis)
						final short height = hgtData[y*res+x]; 
						buf[x*2]   = (byte) ((height & 0xff00) >> 0x8); 
						buf[x*2+1] = (byte) (height & 0x00ff);															
					}
					os.write(buf);
				}		
			} catch (IOException e) {
				throw new RuntimeException(e);
			}finally {
				try { os.close(); } catch (Exception ignored) {}
			}
		}

	}

}
